from rest_framework.generics import GenericAPIView, ListAPIView, RetrieveAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import Goods, GoodsCategory, GoodsAlbum
from goods.serializers import GoodsSerializers, OneGoodsCategoryAlbumSerializer, TwoGoodsCategoryAlbumSerializer, \
    GoodsDetailSerializer, GoodsDetailAlbumSerializer, GoodsDetailCategorySerializer, GoodsListSerializer
    # GoodsCategorySerializer


# 1.1获取商品首页右侧的推荐商品
# URL:/goods/recommend/
# 请求方式：GET
# 请求参数：无
# 返回数据：json格式(校验后的商品数据)
class GoodsListView(APIView):
    def get(self, request):
        # 获取商品右侧推荐商品
        goods = Goods.objects.filter(is_red=1, img_url__isnull=False)[0:4]

        serializers = GoodsSerializers(goods, many=True)
        return Response(serializers.data)


# 1.2获取首页的类别商品
# URL:/goods/category/
# 请求方式：GET
# 请求参数：无
# 返回数据：json
'''[
            {   # 第1个大类别
                'id': 3,
                'title': '互联网媒体',
                'goodscategory_set': [{'id':x1, 'title': '子类别1'}, 
                                     {'id':x2, 'title': '子类别2'}],
                'goods': [{商品1},{商品2}...]
            },
'''


class GoodsCategoryListView(APIView):
    def get(self, request):
        # 得到一级分类
        one_categories = GoodsCategory.objects.filter(parent_id=0).all()
        # 存储所有的大类数据
        goodsData_list_data = []

        for onecategory in one_categories:
            # 序列化第一分类的数据
            one_category_data = OneGoodsCategoryAlbumSerializer(onecategory).data
            # 获取当前第一分类下的所有二级分类
            two_categories = onecategory.goodscategory_set.all()

            # 用于存储二级分类的列表
            goodscategory_set = []
            twogood_id_list = []

            for twocategory in two_categories:
                two_category_data = OneGoodsCategoryAlbumSerializer(twocategory).data
                twogood_id_list.append(two_category_data['id'])
                goodscategory_set.append(two_category_data)

            one_category_data['goodscategory_set'] = goodscategory_set

            # 存储在当前类别下的时间的最新的5条
            category_to5 = Goods.objects.filter(category_id__in=twogood_id_list).order_by('-create_time').exclude(
                img_url='')[0:5]
            goods = TwoGoodsCategoryAlbumSerializer(category_to5, many=True).data
            one_category_data['goods'] = goods
            goodsData_list_data.append(one_category_data)

        return Response(goodsData_list_data)


class GoodsDetailView(APIView):
    def get(self, request, goods_id):
        # 获取商品详情页
        one_goods = Goods.objects.get(id=goods_id)
        one_goods_data = GoodsDetailSerializer(one_goods).data

        goodsalbums = one_goods.goodsalbum_set.all()
        goodsalbums_data = GoodsDetailAlbumSerializer(goodsalbums, many=True).data
        one_goods_data['goodsalbum_set'] = goodsalbums_data

        categories = one_goods.category
        categories_data = GoodsDetailCategorySerializer(categories).data
        one_goods_data['category'] = categories_data

        return Response(one_goods_data)


# 2.	列表页
# URL:/goods/?category=category_id&ordering=-create_time
# 请求方式：GET
# 请求参数：
# 参数          类型      是否必须          说明
# cateroty_id     int         是            类别id（二级类别）
# ordering       str          是         排序关键字(create_time,price)
#
# 返回数据：json


class GoodsListsView(APIView):
    def get(self, request):
        # 获取参数
        category_id = request.query_params.get('category')
        ordering = request.query_params.get('ordering', 'create_time')

        # 从数据库根据前端传递的category_id去数据库取值
        two_category = GoodsCategory.objects.get(id=category_id)

        # 判断前端传递的id是否为二级
        if two_category.parent_id != 0:
            # 说明是二级分类
            two_categorys = Goods.objects.filter(category_id=category_id).order_by(str(ordering)).all()
            serializer = GoodsListSerializer(two_categorys, many=True)

        else:
            # 说明是一级分类 category_id 一级分类id  获取父类id是 category_id分类的二级分类
            two_category1 = GoodsCategory.objects.filter(parent_id=category_id)
            list_obj = []
            for two_category in two_category1:
                two_category1_data = Goods.objects.filter(category_id=two_category.id).order_by(str(ordering)).all()
                list_obj.append(two_category1_data)

            serializer = GoodsListSerializer(list_obj, many=True)

        return Response(serializer.data)





class CategoryListView(APIView):
    def get(self, request, category_id):

        category = GoodsCategory.objects.get(id = category_id)
        if category.parent_id != 0:
            serializer = OneGoodsCategoryAlbumSerializer(category)
        else:
            categorys2 = GoodsCategory.objects.filter(parent_id=category_id)
            serializer = OneGoodsCategoryAlbumSerializer(categorys2, many=True)
        return Response(serializer.data)

